package gek.uni.diplom.integrate.wizard.actions;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.internal.core.PackageFragmentRoot;
import org.eclipse.jdt.internal.ui.browsing.PackagesViewTreeViewer;
import org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider;
import org.eclipse.jdt.internal.ui.packageview.PackageExplorerLabelProvider;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.NavigatorFrameSource;

import RootDesc.RootDescPackage;
import RootDesc.RootDescription;
import RootDesc.TestDescription;

@SuppressWarnings( { "restriction", "restriction" })
public class TestCodeGenerationAction implements IObjectActionDelegate {

  IWorkbenchPart part;

  public TestCodeGenerationAction() {
    part = null;
  }

  @Override
  public void setActivePart(IAction action, IWorkbenchPart targetPart) {
    part = targetPart;
  }

  @Override
  public void run(IAction action) {
    loadEMFResource();
  }

  @SuppressWarnings( { "restriction", "restriction" })
  private void loadEMFResource() {
    ResourceSet resourceSet = new ResourceSetImpl();
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(
        Resource.Factory.Registry.DEFAULT_EXTENSION,
        new EcoreResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(RootDescPackage.eNAME,
        RootDescPackage.eINSTANCE);
    String fileName = "D:\\example_tfg.xml";
    File file = new File(fileName);
    URI uri = URI.createFileURI(file.getAbsolutePath());
    Resource resource = resourceSet.getResource(uri, true);

    RootDescription rootDesc = selectRootDescription(resource);
    if (rootDesc == null) return;
    String classContext = rootDesc.getClassContext();

    ITreeContentProvider contentProvider = new BaseWorkbenchContentProvider() {
      @Override
      public Object[] getChildren(Object element) {
        // if (!(element instanceof IFolder))
        // return super.getChildren(element);
        Object[] children = super.getChildren(element);
        ArrayList<Object> resContainer = new ArrayList<Object>();
        for (Object childObj : children) {
          if (childObj instanceof IFile) {
            if (((IFile) childObj).getFileExtension().equals("java"))
              resContainer.add(childObj);
          } else
            resContainer.add(childObj);
        }
        return resContainer.toArray(new Object[0]);
      }
    };

    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(part.getSite().getShell(),
            new WorkbenchLabelProvider(), contentProvider);
    dialog.setTitle("Выбор расположения исходных кодов");
    dialog.setMessage("Выберите директорию, содержащую исходные коды классов:");
    dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
    dialog.open();

    PackageExplorerContentProvider contentProvider1 =
        new PackageExplorerContentProvider(true) {
          @Override
          public Object[] getChildren(Object parentElement) {
            Object[] parentChildren = super.getChildren(parentElement);
            ArrayList<Object> resultChildrenList = new ArrayList<Object>();
            for (Object child : parentChildren) {
              if (child instanceof IFolder || child instanceof IJavaProject
                  || child instanceof PackageFragmentRoot
                  || child instanceof PackageFragment
                  || child instanceof IProject) resultChildrenList.add(child);
            }
            return resultChildrenList.toArray();
          }
        };
        
    contentProvider1.setIsFlatLayout(false);
    contentProvider1.setShowLibrariesNode(false);
    dialog =
        new ElementTreeSelectionDialog(part.getSite().getShell(),
            new PackageExplorerLabelProvider(contentProvider1),
            contentProvider1);

    dialog.setTitle("Выбор расположения целевого пакета");
    dialog.setMessage("Выберите целевой пакет:");
    dialog.setInput(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()));
    dialog.open();

    EList<TestDescription> testDescriptions = rootDesc.getTestDescriptions();
    for (TestDescription testDesc : testDescriptions) {
      // System.out.println(generateTestMethodCode(rootDesc, testDesc));
      // System.out.println("=======================================");
      // System.out.println("=======================================");
    }
  }

  @Override
  public void selectionChanged(IAction action, ISelection selection) {
  // TODO Auto-generated method stub

  }

  private RootDescription selectRootDescription(Resource resource) {
    for (Iterator<EObject> iterator = resource.getContents().iterator(); iterator
        .hasNext();) {
      EObject obj = iterator.next();
      if (obj instanceof RootDescription) {
        return (RootDescription) obj;
      }
    }
    return null;
  }

}
